package org.hbkj.springbootmybatis.service;

import org.hbkj.springbootmybatis.dao.GoodsDao;
import org.hbkj.springbootmybatis.entity.GoodsDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class GoodsService {
    @Autowired
    private GoodsDao goodsDao;

    public void add(GoodsDo goodsDo) {
        // 可在此处添加默认值设置等逻辑，如库存总数和剩余量默认值
        if (Objects.isNull(goodsDo.getTotal())) {
            goodsDo.setTotal(0);
        }
        if (Objects.isNull(goodsDo.getRemaining())) {
            goodsDo.setRemaining(goodsDo.getTotal());
        }
        goodsDao.insert(goodsDo);
    }

    public void remove(Long id) {
        goodsDao.delete(id);
    }

    public void edit(GoodsDo goodsDo) {
        goodsDao.update(goodsDo);
    }

    public GoodsDo getById(Long id) {
        return goodsDao.selectOne(id);
    }

    public List<GoodsDo> getAll() {
        return goodsDao.selectAll();
    }

    public List<GoodsDo> getByRemaining(Integer remaining) {
        return goodsDao.selectByRemaining(remaining);
    }

    @Transactional
    public boolean deductStock(Long goodsId, Integer purchaseCount) {
        GoodsDo goods = goodsDao.selectOne(goodsId);
        if (goods == null || goods.getRemaining() < purchaseCount) {
            return false; // 库存不足
        }

        // 直接调用DAO，无需设置purchaseCount到GoodsDo对象
        int rows = goodsDao.deductStock(goodsId, purchaseCount);
        return rows > 0;
    }
}